package com.vanzo.tisen.agingtest;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;

import android.annotation.SuppressLint;
import android.content.Context;
import android.util.AttributeSet;
import android.util.Log;
import android.widget.Chronometer;
@SuppressLint(
{ "ViewConstructor", "SimpleDateFormat" })
public class Anticlockwise extends Chronometer
{
	public Anticlockwise(Context context, AttributeSet attrs)
	{
		super(context, attrs);
		mTimeFormat = new SimpleDateFormat("HH:mm:ss");
        mTimeFormat.setTimeZone(TimeZone.getTimeZone("GMT+)"));
		this.setOnChronometerTickListener(listener);
	}

	private long mTime;
	private long mNextTime;

	public long getNextTime() {
		return mNextTime;
	}

	private OnTimeCompleteListener mListener;
	private SimpleDateFormat mTimeFormat;

	public Anticlockwise(Context context)
	{
		super(context);

	}

	public void reStart(long _time_s)
	{
		if (_time_s == -1)
		{
			mNextTime = mTime;
		} else
		{
			mTime = mNextTime = _time_s;
		}
		this.start();
	}

	public void reStart()
	{
		reStart(-1);
	}

	public void onResume()
	{
		this.start();
	}

	public void onPause()
	{
		this.stop();
	}

	public void setTimeFormat(String pattern)
	{
		mTimeFormat = new SimpleDateFormat(pattern);
	}

	public void setOnTimeCompleteListener(OnTimeCompleteListener l)
	{
		mListener = l;
	}

	OnChronometerTickListener listener = new OnChronometerTickListener()
	{
		@Override
		public void onChronometerTick(Chronometer chronometer)
		{
			if (mNextTime <= 0)
			{
				if (mNextTime == 0)
				{
					Anticlockwise.this.stop();
					if (null != mListener)
						mListener.onTimeComplete();
				}
				mNextTime = 0;
				updateTimeText();
				return;
			}

			mNextTime--;

			updateTimeText();
		}
	};

	public void initTime(long _time_s)
	{
		mTime = mNextTime = _time_s;
		updateTimeText();
	}
	
	private void updateTimeText()
	{
		Log.d("time","time:"+mNextTime);
		this.setText(time2Text(mNextTime));
		//this.setText(mTimeFormat.format(new Date((mNextTime +1)* 1000)));
	}
	private String time2Text(long time){
		int second = (int) (time%60);
		int min = (int) ((time/60)%60);
		int hour = (int) ((time/3600)%60);
		return hour+":"+min+":"+second;
	}
	public interface OnTimeCompleteListener
	{
		void onTimeComplete();
	}

}
